from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection
from rest_framework.generics import GenericAPIView

from celery_tasks.sms.tasks import send_sms_code
from meiduo_big.libs.captcha.captcha import captcha
from verifications.serializers import ImageCodeCheckSerializer
from . import constants
from django.http import HttpResponse
import random
import logging
# Create your views here.


logger = logging.getLogger('django')
# /image_codes/(?P<image_code_id>[\w-]+)/


class ImageCodeView(APIView):
    # 图片验证码
    def get(self, request, image_code_id):
        text, image = captcha.generate_captcha()
        redis_conn = get_redis_connection('verify_codes')
        pl = redis_conn.pipeline()
        pl.setex('img_%s' % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
        pl.execute()
        return HttpResponse(image, content_type='images/jpg')


# /sms_codes/(?P<mobile>1[3-9]\d{9})/?image_code_id=xxx&text=xxx
class SMSCodeView(GenericAPIView):
    serializer_class = ImageCodeCheckSerializer

    def get(self, request, mobile):
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)
        # 生成随机六位数
        sms_code = '%06d' % random.randint(0, 999999)
        print(sms_code)
        # 记住，存到数据库中
        # 获取数据库对象
        redis_conn = get_redis_connection('verify_codes')
        # 创建管道
        pl = redis_conn.pipeline()
        # 保存五分钟的手机验证码
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 保存一分钟的验证码发送时间
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        # 执行管道
        pl.execute()
        # try:
        #     ccp = CCP()
        #     # ccp.send_template_sms('18516952650', ['1234', 5], 1)
        #     expires = constants.SMS_CODE_REDIS_EXPIRES // 60
        #     result = ccp.send_template_sms(mobile, [sms_code, expires], constants.SMS_CODE_TEMP_ID)
        # except Exception as e:
        #     logger.error("发送验证码短信[异常][ mobile: %s, message: %s ]" % (mobile, e))
        #     return Response(data={'message': 'failed'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        # else:
        #     if result == 0:
        #         logger.info("发送验证码短信[正常][ mobile: %s ]" % mobile)
        #         return Response(data={'message': 'ok'}, status=status.HTTP_200_OK)
        #     else:
        #         logger.warning("发送验证码短信[失败][ mobile: %s ]" % mobile)
        #         return Response(data={'message': 'error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        # (mobile, code, expires, temp_id):
        expires = str(constants.SMS_CODE_REDIS_EXPIRES // 60)
        send_sms_code.delay(mobile, sms_code, expires, constants.SMS_CODE_TEMP_ID)
        return Response(data={'message': 'ok'}, status=status.HTTP_200_OK)


